package com.easychat.aspect;

import com.alibaba.fastjson.JSON;
import org.apache.coyote.Request;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author Dongdong
 * @  打印方法入参 ，地址，方法名
 */
@Component
@Aspect//声明为切面
public class LxdLogAspect {
    private Logger logger = org.slf4j.LoggerFactory.getLogger(LxdLogAspect.class);
    /**
     * 定义切点，切入点为com.easychat.service包下所有类的方法
     */
    @Pointcut("@annotation(com.easychat.annotation.LxdLog)")
    public void lxdLog(){}

    //  joinPoint 为具体的方法名
    @Before("lxdLog()")
    public void beforeLog(JoinPoint joinPoint){
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        String methodName = joinPoint.getSignature().getName();
        HttpServletRequest request = requestAttributes.getRequest();
        //打印请求地址
        logger.info("请求地址:{}", request.getRequestURL().toString());
        //打印请求参数
        logger.info("入参:{}",JSON.toJSONString(joinPoint.getArgs()));
        //打印请求方法
        logger.info("执行路径及方法:{}",joinPoint.getSignature().getDeclaringTypeName() + "." + methodName);
    }
    @After(value = "lxdLog()")
    public void afterLxdLog(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        logger.info("{}方法结束!!!!",methodName);
    }

}
